<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from 'vue'
import {
  reqAddOrUpdateRole,
  reqAllMenuList,
  reqAllRoles,
  reqAssignPermission,
  reqDeleteRole,
} from '@/api/acl/role'
import {
  MenuDataList,
  MenuResponseData,
  RoleData,
  RoleDataList,
  RoleResponseData,
} from '@/api/acl/role/type.ts'
import useLayOutSettingStore from '@/store/modules/setting.ts'
import { ElMessage } from 'element-plus'
// 当前页码
let pageNo = ref<number>(1)
// 一页展示几条数据
let pageSize = ref<number>(10)
onMounted(() => {
  getHasRoles()
})
// 搜索角色用的关键字
let keyword = ref<string>('')
// 存储服务器响应的角色list
let allRole = ref<RoleDataList>([]) // () 没有初始值在之后的使用中会报undefined
// 角色总个数
let total = ref<number>(0)
/**
 * 获取角色请求
 * @param pager
 */
const getHasRoles = async (pager = 1) => {
  pageNo.value = pager
  let result: RoleResponseData = await reqAllRoles(
    pageNo.value,
    pageSize.value,
    keyword.value,
  )
  if (result.code == 200) {
    allRole.value = result.data.records
    total.value = result.data.total
  }
}
const handleSizeChange = () => {
  getHasRoles()
}
const search = () => {
  // 搜索角色
  getHasRoles()
  // 清空
  keyword.value = ''
}
// 引入layout仓库
const settingStore = useLayOutSettingStore()
const reset = () => {
  settingStore.refresh = !settingStore.refresh
}
// 对话框显示与隐藏
let dialogVisible = ref<boolean>(false)
/**
 * 添加角色
 */
const addRole = () => {
  dialogVisible.value = true
  // 清空数据   id也得清掉，id没定义初始值，但是在修改操作时会加上
  Object.assign(RoleParams, { roleName: '', id: '' })
  // 清理校验信息
  nextTick(() => {
    formRef.value.clearValidate('roleName')
  })
}
/**
 * 修改角色
 * @param row
 */
const updateRole = (row: RoleData) => {
  // 显示出对话框
  dialogVisible.value = true
  // 存储已有的职位
  Object.assign(RoleParams, row)
  // 清理校验信息
  nextTick(() => {
    formRef.value.clearValidate('roleName')
  })
}
// 收集新增岗位数据
let RoleParams = reactive<RoleData>({
  roleName: '',
})
// 自定义校验规则的回调
const validatorRoleName = (_rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('角色名称不能少于2个字符'))
  }
}
// 校验规则
const rules = {
  roleName: [{ required: true, trigger: 'blur', validator: validatorRoleName }],
}
// 对话框表单组件实例
const formRef = ref<any>()
/**
 * 对话框确定按钮点击事件
 */
const save = async () => {
  // 校验
  await formRef.value.validate()
  // 发请求
  const result: any = await reqAddOrUpdateRole(RoleParams)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: RoleParams.id ? '更新成功' : '添加成功',
    })
    dialogVisible.value = false
    // 新增回到第一页，修改回到当前页
    if (RoleParams.id) {
      await getHasRoles(pageNo.value)
    } else {
      await getHasRoles()
    }
  }
}
// 控制抽屉显示与隐藏
const drawer = ref<boolean>(false)
// 收集当前要分类权限的职位的数据
let RoleParams2 = reactive<RoleData>({
  roleName: '',
})
const defaultProps = {
  children: 'children',
  label: 'name',
}
// 收集勾选的4级节点的id  ，因为树形控件特性，只需要控制4级节点的勾选状态即可
const selectArr = ref<number[]>([])
let menuArr = ref<MenuDataList>()
const setPermission = async (row: RoleData) => {
  drawer.value = true
  // 收集当前要分类权限的职位的数据
  Object.assign(RoleParams2, row)
  // 获取当前职位已有的权限
  const result: MenuResponseData = await reqAllMenuList(
    RoleParams2.id as number,
  )
  if (result.code == 200) {
    // 存储权限数据
    menuArr.value = result.data

    // 递归、把四层 已有的权限id存储到数组中
    selectArr.value = filterSelectArr(menuArr.value, [])
    // console.log(selectArr.value)
  }
}
// 递归,把四层已有的权限id存储到数组中
const filterSelectArr = (allData: any, initArr: any) => {
  allData.forEach((item: any) => {
    if (item.select && item.level == 4) {
      // 只收集第4层的
      initArr.push(item.id)
    }
    if (item.children && item.children.length > 0) {
      // 如果有子节点，继续递归
      filterSelectArr(item.children, initArr)
    }
  })
  return initArr
}
// 权限树组件实例🌳
const treeRef = ref<any>()
const handlerConfirmAssignPermissions = async () => {
  // 准备参数
  const id: any = RoleParams2.id
  // 后端需要收集所有选中的节点id，包括父节点
  let arr = treeRef.value.getHalfCheckedKeys() // 半选中的节点
  let arr2 = treeRef.value.getCheckedKeys() // 选中的节点
  // 发请求
  const result: any = await reqAssignPermission(id, arr.concat(arr2))
  if (result.code == 200) {
    drawer.value = false
    ElMessage({ type: 'success', message: '分配权限成功' })
    // 如果当前用户权限修改得刷新页面，获取最新权限能看到的页面
    window.location.reload()
  }
}
// 删除已有的职位
const removeRole = async (id: number) => {
  let result: any = await reqDeleteRole(id)
  if (result.code == 200) {
    // 提示信息
    ElMessage({ type: 'success', message: '删除成功' })
    await getHasRoles(
      allRole.value.length > 1 ? pageNo.value : pageNo.value - 1,
    )
  }
}
</script>

<template>
  <div>
    <el-card style="height: 80px">
      <el-form inline class="form">
        <el-form-item label="搜索角色">
          <el-input placeholder="请你输入角色名称" v-model="keyword"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="default"
            :disabled="!keyword"
            @click="search"
          >
            查询
          </el-button>
          <el-button type="primary" size="default" @click="reset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin: 10px 0">
      <el-button type="primary" size="default" icon="Plus" @click="addRole">
        添加角色
      </el-button>
      <el-table border style="margin: 10px 0" :data="allRole">
        <el-table-column type="index" align="center" label="#" />
        <el-table-column align="center" label="ID" prop="id" />
        <el-table-column align="center" label="职位名称" prop="roleName" />
        <el-table-column
          align="center"
          label="创建时间"
          prop="createTime"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          label="更新时间"
          prop="updateTime"
          show-overflow-tooltip
        />
        <el-table-column align="center" label="操作" width="280px">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              icon="User"
              @click="setPermission(row)"
            >
              分配权限
            </el-button>
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateRole(row)"
            >
              编辑
            </el-button>
            <el-popconfirm
              :title="`Are you sure to delete the ${row.roleName}?`"
              width="260px"
              @confirm="removeRole(row.id)"
            >
              <template #reference>
                <el-button type="primary" size="small" icon="Delete">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="getHasRoles"
      />
    </el-card>
    <el-dialog
      :title="RoleParams.id ? '更新角色' : '新增角色'"
      v-model="dialogVisible"
    >
      <el-form :model="RoleParams" :rules="rules" ref="formRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            placeholder="请你输入角色名称"
            v-model="RoleParams.roleName"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="save">Confirm</el-button>
        </div>
      </template>
    </el-dialog>
    <!--  抽屉组件：分配角色的菜单权限和按钮权限-->
    <el-drawer v-model="drawer">
      <template #header>
        <h4>分配权限</h4>
      </template>
      <template #default>
        <el-tree
          ref="treeRef"
          style="max-width: 600px"
          :data="menuArr"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="selectArr"
          :props="defaultProps"
        />
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawer = false">Cancel</el-button>
          <el-button type="primary" @click="handlerConfirmAssignPermissions">
            Confirm
          </el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<style scoped lang="scss">
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
